'use strict';

const MYSQL_TABLE = 'record';
const { ACTION_MEANING } = require('../constants/actionType');
const ERR_CODE = require('../constants/errorCode');
const Service = require('egg').Service;

class RecordService extends Service {
  async create(userId, actionType, extInfo) {
    const { ctx, app } = this;
    try {
      const result = await app.mysql.insert(MYSQL_TABLE, {
        user_id: userId,
        action_type: ACTION_MEANING[actionType],
        ext_info: extInfo,
        create_time: app.mysql.literals.now,
      });

      if (result.affectedRows !== 1) throw (ERR_CODE.Record_DBInsertFail);
    } catch (err) {
      switch (err) {
        case ERR_CODE.Record_DBInsertFail:
          ctx.throw(422, '数据库插入失败，操作记录创建失败', {
            errCode: ERR_CODE.Record_DBInsertFail,
            description: '数据库插入失败',
          });
          break;
        default:
          throw (err);
      }
    }
  }

  async index(userId, page, size, order) {
    const { app } = this;
    const orderStr = order === 1 ? 'desc' : 'asc';
    const result1 = await app.mysql.select(MYSQL_TABLE, {
      where: { user_id: userId }, // 查询条件
      columns: [ 'record_id', 'action_type', 'ext_info', 'create_time' ], // 要查询的表字段
      orders: [[ 'create_time', orderStr ]], // 排序方式
      limit: size, // 返回数据量
      offset: (page - 1) * size, // 数据偏移量
    });

    const sql = `SELECT count(*) as total from ${MYSQL_TABLE} where user_id = '${userId}';`;
    const result2 = await app.mysql.query(sql);
    console.log(result1);
    return { list: result1, total: result2[0].total };
  }
}

module.exports = RecordService;
